from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework import status
from django_redis import get_redis_connection

from .models import User, Address
from goods.models import SKU
from goods.serializers import SKUSerializer
from . import constants
from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, AddressTitleSerializer, AddUserBrowsingHistorySerializer


class UserBrowsingHistoryView(CreateAPIView):
    """用户浏览历史记录"""

    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """查询用户浏览记录"""
        user_id = request.user.id

        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 查询历史记录
        history = redis_conn.lrange("history_%s" % user_id, 0, -1)
        skus = []
        # 查询出浏览记录中每个商品SKU对象
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        # 对查询到的商品SKU对象进行序列化
        ser = SKUSerializer(skus, many=True)

        return Response(ser.data)


class AddressViewSet(UpdateModelMixin, CreateModelMixin, GenericViewSet):
    """
    收货地址视图集
    在此处直接继承UpdateModelMixin，就可以更新收货地址
    """

    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]  # 只有登录成功的用户才能有权限创建收货地址

    """
    因为需要先判断收货地址的数量是否超过要求的上限，所以需要重写CreateModelMixin中的create方法
    """
    def create(self, request, *args, **kwargs):
        """新增用户收件地址"""
        count = request.user.addresses.count()  # 查询出当前用户收货地址的数量
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '收货地址数量已达上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def get_queryset(self):
        """重写get_queryset方法，因为需要对收货地址的状态进行过滤"""
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """展示用户收件地址"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """删除收货地址"""
        address = self.get_object()

        # 逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """设置默认地址"""
        address = self.get_object()

        # 设置默认地址
        request.user.default_address = address
        request.user.save()

        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """修改标题"""
        address = self.get_object()

        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)  # 修改后的数据要返回给前端响应


class VerifyEmailView(APIView):
    """邮箱验证"""

    def get(self, request):
        # 从请求的url中提取参数token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少参数token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'Ok'})


class EmailView(UpdateAPIView):
    """保存用户邮箱"""
    serializer_class = EmailSerializer
    # 校验当前用户的权限
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """重写get_object方法"""
        return self.request.user


class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = UserDetailSerializer
    # 校验当前用户的权限
    permission_classes = [IsAuthenticated]

    # 应为在 RetrieveAPIView 中查找对应的user模型需要穿传入参数 pk ，但是在此处没有 pk 传入，所以需要重写get_object()方法,使用request.user属性获取user对象
    def get_object(self):
        """重写get_object方法"""
        return self.request.user


class UserView(CreateAPIView):
    """注册"""

    serializer_class = CreateUserSerializer


class MobileCountView(APIView):
    """判断手机号是否存在"""

    def get(self, request, mobile):
        """
        查询指定手机号码的数量
        :param request:
        :param mobile: 手机号码
        :return: mobile ， count
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count,
        }
        return Response(data)


# 因为该视图中没有操作数据库，也不需要序列化器，所以父类使用APIView
# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """判断用户名是否存在"""

    def get(self, request, username):
        """

        GET usernames/(?P<username>\w{5,20})/count/

        :param request:
        :param username: 用户名
        :return: username , count（用户数量）
        """
        # 查询出指定用户名的数量
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count,
        }
        return Response(data)